package com.open.web.config;

import com.open.basic.util.DateUtil;
import io.swagger.v3.oas.models.media.DateTimeSchema;
import io.swagger.v3.oas.models.media.IntegerSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.oas.models.servers.Server;
import org.springdoc.core.customizers.OpenApiCustomiser;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.Map;

/**
 * API文档配置
 */
@Configuration
public class ApiDocConfig {

    /**
     * 文档配置
     * @return
     */
    @Bean
    public OpenApiCustomiser openApiCustomiser() {
        // Server server = new Server();
        // server.setUrl("");
        // var serverList = List.of(server);
        // return openApi -> openApi.servers(serverList).getComponents().getSchemas().forEach((s, schema) -> {
        return openApi -> openApi.getComponents().getSchemas().forEach((s, schema) -> {
            Map<String, Schema> properties = schema.getProperties();
            if (properties == null) {
                properties = Map.of();
            }
            for (String propertyName : properties.keySet()) {
                Schema propertySchema = properties.get(propertyName);
                if (propertySchema instanceof DateTimeSchema) {
                    properties.replace(propertyName, new StringSchema()
                            .example(DateUtil.getCurrentTime())
                            .pattern("^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$")
                            .description(propertySchema.getDescription()));
                }else if (propertySchema instanceof StringSchema) {
                    properties.replace(propertyName, new StringSchema()
                            .example("")
                            .pattern(propertySchema.getPattern())
                            .description(propertySchema.getDescription()));
                }else if (propertySchema instanceof IntegerSchema) {
                    properties.replace(propertyName, new IntegerSchema()
                            .example(propertySchema.getDefault())
                            .pattern(propertySchema.getPattern())
                            .description(propertySchema.getDescription()));
                }
            }
        });
    }


}
